(function () {
	
	$("#avatar").error(function() { 
		$(this).attr("src", "../img/upload.png"); 
		$(this).error=null;
	});
	
	var image;
	
	$("body").on("change","#file",function() {
		var $file = $(this);
		var fileObj = $file[0];
		var windowURL = window.URL || window.webkitURL;
		var dataURL;
		var $img = $("#avatar");

		if (fileObj && fileObj.files && fileObj.files[0]) {
			dataURL = windowURL
					.createObjectURL(fileObj.files[0]);
		} else {
			dataURL = $file.val();
			var imgObj = document.getElementById("preview");
			// 两个坑:
			// 1、在设置filter属性时，元素必须已经存在在DOM树中，动态创建的Node，也需要在设置属性前加入到DOM中，先设置属性在加入，无效；
			// 2、src属性需要像下面的方式添加，上面的两种方式添加，无效；
			imgObj.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale)";
			imgObj.filters
					.item("DXImageTransform.Microsoft.AlphaImageLoader").src = dataURL;
		}

		// 限制上传图片像素大小
		image = new Image();
		image.src = dataURL;
		image.onload = function() {
			var height = image.height;
			var width = image.width;
			if (width > 30 && height > 30) {
				message('请上传30*30像素');
				$file.val("");
				return false;
			}
			$img.attr('src', dataURL);
		}
	});

	jQuery('#fileclick').on('click', function() {
		return $("#file").click();
	});

	//所选部件层级类型
	var partType = '';
    //table数据显示
    var serverData = {};
    var	serverTable;
    var serverData2 = {};
    serverData2.partId = '';
    var	serverTable2;
    jQuery(document).ready(function () {
        serverTable=  jQuery('#dataTable').DataTable({
            "serverSide": true,
            "ordering": false,
            "ajax": {
                "dataType": "json",
                "type": "post",
                "cache": false,
                "url": window.rootPath+'/ui/bindingpart/getpage',
                "data": function (d) {
                    return $.extend({}, d, serverData);
                }
            },
            columns: [
	        		{
	            data: null,
	            defaultContent: ""
	        		},
	        		{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="addDate"/>';
                        return operate;
                    }
	        		},
	            {
	            data: 'partName'
	            },
	            {
	            data: 'manufacturer'
	            },
	            {
	            	data: 'productionTime',
	            	render: function (data, type, full, meta) {
	                    if (data)
	                        return moment(data).format('YYYY/MM/DD');
	                    else
	                        return '';
	                }
	            },
	            {
	            	data: 'installationTime',
	            	render: function (data, type, full, meta) {
	                    if (data)
	                        return moment(data).format('YYYY/MM/DD');
	                    else
	                        return '';
	                }
	            },
	            {
	            	data: 'division.divisionName',
	            },
	            {
	            	data: 'part.partName'
	            },
	            {
	            	data: 'state.title'
	            },
                {
                    data:null,
                    defaultContent: "",
                    render: function(data, type, full, meta){
                        var operate = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>'
                        		+ '<button type="button" class="btn btn-sm btn-info addNode" title="绑定"><i class="fa fa-sign-in"></i></button>';

                        return operate;

                    }
                }],
            "drawCallback": function ( oSettings ) {
                var k = 0;
                var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;

                for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
                {
                    $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
                    k++;
                }

                serverTable.off('click','tr');
                serverTable.on( 'click', 'tr', function (event) {
                    event=event||window.event;
                    var target=event.target||event.scrElement;
                    var data = serverTable.row( this ).data();

                    if(target.className.indexOf('fa-pencil')!=-1||target.className.indexOf('editBtn')!=-1){
    						editInfo(data);
                    }
                    if(target.className.indexOf('fa-sign-in')!=-1||target.className.indexOf('addNode')!=-1){
                        bindingPart(data,data.partName);
                    }
                    return;
                } );
            }
        });
        
        serverTable2 = jQuery('#dataTable2').DataTable({
	        	"serverSide": true,
	        	"ordering": false,
	        	"ajax": {
	        		"dataType": "json",
	        		"type": "post",
	        		"cache": false,
	        		"url": window.rootPath+'/ui/bindingpart/getpagebypart',
	        		"data": function (d) {
	        			return $.extend({}, d, serverData2);
	        		}
	        	},
	        	columns: [
	        		{
	        			data: null,
	        			defaultContent: ""
	        		},
	        		{
                    data: 'id',
                    render: function (data, type, full, meta) {
                        var operate ='<input type="checkbox" dataId="'+data+'" group="removeDate"/>';
                        return operate;
                    }
	        		},
	        		{
	        			data: 'partName'
	        		},
	        		{
	        			data: 'manufacturer'
	        		},
	        		{
	        			data: 'productionTime',
	        			render: function (data, type, full, meta) {
	        				if (data)
	        					return moment(data).format('YYYY/MM/DD');
	        				else
	        					return '';
	        			}
	        		},
	        		{
	        			data: 'installationTime',
	        			render: function (data, type, full, meta) {
	        				if (data)
	        					return moment(data).format('YYYY/MM/DD');
	        				else
	        					return '';
	        			}
	        		},
	        		{
	        			data: 'division.divisionName',
	        		},
	        		{
	        			data: 'part.partName'
	        		},
	        		{
	        			data: 'interfaceAddress'
	        		},
	        		{
	        			data: 'interfacePort'
	        		},
	        		{
	        			data: 'state.title'
	        		},
	        		{
        			data:null,
        			defaultContent: "",
        			render: function(data, type, full, meta){
        				var edit = '<button type="button" class="btn btn-sm btn-info editBtn" title="编辑"><i class="fa fa-pencil"></i></button>';
        				var operate = '<button type="button" class="btn btn-sm btn-info addNode" title="移除"><i class="fa fa-remove"></i></button>';
//        				if(partType == '1'){
//        					operate = edit + operate;
//        				}
        				operate = edit + operate;
        				return operate;
        				
        			}
        		}],
        		"drawCallback": function ( oSettings ) {
        			var k = 0;
        			var total = oSettings.aiDisplay.length + oSettings._iDisplayStart;
        			
        			for ( var i=oSettings._iDisplayStart, iLen=total ; i<iLen ; i++ )
        			{
        				$('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[k] ].nTr ).text( i+1 );
        				k++;
        			}
        			
        			serverTable2.off('click','tr');
        			serverTable2.on( 'click', 'tr', function (event) {
        				event=event||window.event;
        				var target=event.target||event.scrElement;
        				var data = serverTable2.row( this ).data();
        				
        				if(target.className.indexOf('fa-pencil')!=-1||target.className.indexOf('editBtn')!=-1){
        					editInfo(data);
                    }
        				if(target.className.indexOf('fa-remove')!=-1||target.className.indexOf('addNode')!=-1){
        					unbind(data,data.partName);
        				}
        				return;
        			} );
        		}
        });
        
        //初始 不显示 视频扩展信息
        fnShowHide(7,false);
    		fnShowHide(8,false);
        
        //查询
        jQuery('.searchBtn').on('click',function(){
            serverData.key=jQuery('#search').val();
            serverTable.draw();
        })
        
        //撤销查询
        jQuery('.resetBtn').on("click",function()
        {
            jQuery('#search').val('');
            serverData.key ='';
            serverTable.draw();
        });
        
        //查询2
        jQuery('.searchBtn2').on('click',function(){
        		var id = serverData2.partId;
        		if(id == '' || id == '0'){
        			message("请选择部件区域!");
        			return;
        		}
        		serverData2.key=jQuery('#search').val();
        		serverTable2.draw();
        })
        
        //撤销查询2
        jQuery('.resetBtn2').on("click",function(){
	        	jQuery('#search2').val('');
	        	serverData2.key ='';
	        	serverTable2.draw();
    		});
        
        //绑定视频部件扩展信息
        jQuery('.bindingBtn').on('click',function(){
            if(jQuery("#modalForm") && !jQuery("#modalForm").Validform({tiptype:3, showAllError:true}).check(false)){
                return;
            };
            var data={
                    id:jQuery('#id').val(),
                    partId:serverData2.partId,
                    interfaceAddress:jQuery('#interfaceAddress').val(),
                    interfacePort:jQuery('#interfacePort').val()
                };
                var url=window.rootPath+'/ui/bindingpart/bindvideoinfo';
                $("#right").mLoading("show");
                jQuery.ajax({
                    url:encodeURI(url),
                    type:'post',
                    data:JSON.stringify(data),
                    dataType:'json',
                    contentType:'application/json;charset=utf-8',
                    success: function (data) {
                        jQuery('#Modal').modal('hide');
                        serverTable.draw(false);
                        serverTable2.draw(false);
                        message(data.msg);
                        $("#right").mLoading("hide");
                    }
                });
        });
        
        //保存已绑定部件信息
        jQuery('.saveBtn').on('click',function(){
	        	if(jQuery("#editModalForm") && !jQuery("#editModalForm").Validform({tiptype:3, showAllError:true}).check(false)){
	        		return;
	        	};
	        	
	        	if(!$("#videoInfoDiv").is(":hidden")){
	        	  	if(jQuery("#videoModalForm") && !jQuery("#videoModalForm").Validform({tiptype:3, showAllError:true}).check(false)){
		        		return;
		        	};
	        	}
		    var interfaceAddress = $('#interfaceAddress1').val();
			var interfacePort = $('#interfacePort1').val();
			
	        var id = jQuery('#partId').val();
	        var partName = jQuery('#partName').val();
	        var manufacturer = jQuery('#manufacturer').val();
	        var productionTime = jQuery('#productionTime').val() + ' 00:00:00';
	        var installationTime = jQuery('#installationTime').val()+ ' 00:00:00';
	        var stateId = jQuery('#state').val();
	        var deviceIdentify = jQuery('#deviceIdentify').val();
			
			var data = {
					"id" : id,
					"partName" : partName,
					"manufacturer" : manufacturer,
					"productionTime" : new Date(productionTime),
					"installationTime" : new Date(installationTime),
					"state" : stateId,
					"deviceIdentify" : deviceIdentify,
					"interfaceAddress" : interfaceAddress,
					"interfacePort" : interfacePort
				}
			var url=window.rootPath+'/ui/bindingpart/savePartBaseInfoWithFile';
			$("#right").mLoading("showNoIcon");
			$.ajaxFileUpload({
				url : url,
				secureuri : false,// 是否需要安全协议
				fileElementId : [ "file" ],// 文件上传的Id属性
				dataType : 'text',
				data : data,
				success : function(){
					jQuery('#editModal').modal('hide');
					serverTable.draw(false);
					serverTable2.draw(false);
					message("保存信息成功！");
					$("#right").mLoading("hide");
				}
			})
			
//	        	var url=window.rootPath+'/ui/bindingpart/save';
//	        	jQuery.ajax({
//	        		url:encodeURI(url),
//	        		type:'post',
//	        		data:JSON.stringify(data),
//	        		dataType:'json',
//	        		contentType:'application/json;charset=utf-8',
//	        		success: function () {
//	        			jQuery('#editModal').modal('hide');
//	        			serverTable2.draw(false);
//	        		}
//	        	});
        });
        
    });

    
    //未绑定 全选
    $("#allNotBound").click(function() {
    		var addDate = $(":checkbox[group=addDate]");
        if ($(this).prop("checked")) {
        		addDate.each(function() {
                $(this).prop("checked", true);  
            });  
        } else {  
        		addDate.each(function() {  
                $(this).prop("checked", false);  
            });  
        }  
    }); 
    
    //已绑定 全选
    $("#allBound").click(function() {
	    	var removeDate = $(":checkbox[group=removeDate]");
	    	if ($(this).prop("checked")) {
	    		removeDate.each(function() {
	    			$(this).prop("checked", true);  
	    		});  
	    	} else {  
	    		removeDate.each(function() {  
	    			$(this).prop("checked", false);  
	    		});  
	    	}  
    }); 
    
    //获取全选数据
    function getSelectData(group){
    		var obj = $(":checkbox[group="+group+"]:checked");
    		var myArray = new Array();
    		var i =0;
    		obj.each(function() {
    			myArray[i++] = $(this).attr('dataId');
    		});
    		return myArray;
    }
    
    //绑定全部信息
    jQuery('.addBtn').on('click', function() {
		var id = serverData2.partId;
		if(id == '' || id == '0'){
			message("请选择部件区域!");
			return;
		}
	    	var dataInfo = getSelectData('addDate');
	    	if(dataInfo.length == 0){
	    		message('请选择需要绑定的部件信息!');
			return;
	    	}
	    	var d = {
	    			"Id" : id,
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/bindingpart/addDataAll';
	    	$("#right").mLoading("show");
        jQuery.ajax({
            url:encodeURI(url),
            cache:false,
            type :"post",
            data: JSON.stringify(d),
            dataType:"json",
            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
            success:function(data){
            		$("#allNotBound").prop("checked", false); 
            		$("#allBound").prop("checked", false); 
				message(data.msg);
				serverTable.draw(false);
				serverTable2.draw(false);
				$("#right").mLoading("hide");
            }
        });
    });
    
    //移除全部信息
    jQuery('.deleteBtn').on('click', function() {
    		var dataInfo = getSelectData('removeDate');
		if(dataInfo.length == 0){
			message('请选择需要移除的部件信息!');
			return;
		}
	    	var d = {
	    			"dataInfo" : dataInfo
	    		};
	    	var url = window.rootPath +'/ui/bindingpart/removeDataAll';
	    	$("#right").mLoading("show");
	    	jQuery.ajax({
	    		url:encodeURI(url),
	    		cache:false,
	    		type :"post",
	    		data: JSON.stringify(d),
	    		dataType:"json",
	    		contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	    		success:function(data){
	    			$("#allNotBound").prop("checked", false); 
            		$("#allBound").prop("checked", false); 
	    			message(data.msg);
	    			serverTable.draw(false);
				serverTable2.draw(false);
				$("#right").mLoading("hide");
	    		}
	    	});
    });
    
    
    ////////////////初始化模型的树结构/////////////////////////
    var modalSetting = {
        edit:{
            enable: false,
            showRemoveBtn:false,
            showRenameBtn:false,
        },
        data: {
            simpleData: {
                enable: true,
                idKey: "id",
                pIdKey: "parentId",
                rootParentId: 0
            }
        },
        view:{
            showLine:true
        },
        check: {
			enable: false,
			chkStyle: "radio",
			radioType: "level"
		},
        callback:{
            onClick:getPartBaseInfo
        }

    };
    
    function getPartBaseInfo(e, treeId, treeNode){
    		var Id=treeNode.id;
		if('0' == Id) return;
		partType = treeNode.partType;
		serverData2.partId =Id;
		
		serverTable2.draw();
		if(partType == '0'){
			fnShowHide(7,false);
			fnShowHide(8,false);
		}else if(partType == '1'){
			fnShowHide(7,true);
			fnShowHide(8,true);
		}
		
    }
    
    
    //初始化 层级树
    var primaryNode=[];
    var url = window.rootPath +'/ui/bindingpart/getAllNodes';
    jQuery.ajax({
        url:url,
        cache:false,
        type :"get",
        data:'',
        dataType:"json",
        contentType:'application/json;charset=utf-8',//解决返回数据中的中文乱码问题
        success:function(data){
            primaryNode.push(
                {
                    id: 0,
                    name: "部件层级",
                    open: "true"
                    // iconSkin:"diy03"
                }
            );
            for (var i = 0; i < data.nodes.length; i++) {
                primaryNode.push(data.nodes[i]);
            }
            $.fn.zTree.init($("#partTree"),modalSetting,primaryNode);
        }
    });
    
    //绑定数据
    function bindingPart(data,levelName){
        var treeObj= $.fn.zTree.getZTreeObj("partTree");
        var selectNodes=treeObj.getSelectedNodes(treeObj);
        var selectNode=selectNodes[0];
        if(selectNode){
        		if(selectNode.id == '0'){
        			message('不能绑定到此层级!');
        			return;
        		}
        		if(partType == '0'){
	            $.springLemonDialog({
	                title:'系统提示',//标题   默认为   系统提示
	                content:'是否要绑定'+levelName+'节点？',//确认文本
	                bootstrapModalOption:{keyboard: true},
	                clickButton:function(sender,modal,index){//按钮事件处理
	                    //index:0 确认    1：取消
	                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
	                    if(index==0){
	                        var url=window.rootPath+'/ui/bindingpart/binding';
	                        var d = {
	                                "partId":selectNode.id,
	                                "id":data.id
	                            };
	                        $("#right").mLoading("show");
	                        jQuery.ajax({
	                            url:encodeURI(url),
	                            cache:false,
	                            type :"post",
	                            data: JSON.stringify(d),
	                            dataType:"json",
	                            contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
	                            success:function(data){
	                            		message(data.msg);
	                                serverTable.draw(false);
	                                serverTable2.draw(false);
	                                $("#right").mLoading("hide");
	                            }
	                        });
	                    }
	                    $(this).closeDialog(modal);
	                }
	            });
        		}else if(partType == '1'){//视频部件
        			jQuery('#id').val(data.id);
        			jQuery('#interfaceAddress').val(data.interfaceAddress);
        			jQuery('#interfacePort').val(data.interfacePort);
        			jQuery('#Modal').modal('show');
        		}
        }
        else{
            $.springLemonDialog({
                title:'系统提示',//标题   默认为   系统提示
                content:'请选择一个节点',//确认文本
                bootstrapModalOption:{keyboard: true},
                clickButton:function(sender,modal,index){//按钮事件处理
                    //index:0 确认    1：取消
                    //sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
                    $(this).closeDialog(modal);
                }

            });
        }
    }
    
    //解绑数据
    function unbind(data,levelName){
    		var treeObj= $.fn.zTree.getZTreeObj("partTree");
    		var selectNodes=treeObj.getSelectedNodes(treeObj);
    		var selectNode=selectNodes[0];
    		$.springLemonDialog({
    			title:'系统提示',//标题   默认为   系统提示
    			content:'是否解除绑定'+levelName+'？',//确认文本
    			bootstrapModalOption:{keyboard: true},
    			clickButton:function(sender,modal,index){//按钮事件处理
    				//index:0 确认    1：取消
    				//sender:事件源 如按钮，sender.html()可得到按钮文字如：取消
    				if(index==0){
    					var url=window.rootPath+'/ui/bindingpart/unbind/'+data.id;
    					$("#right").mLoading("show");
    					jQuery.ajax({
    						url:encodeURI(url),
    						cache:false,
    						type :"post",
    						data: '',
    						dataType:"json",
    						contentType:"application/json;charset=utf-8",//解决返回数据中的中文乱码问题
    						success:function(data){
    							message(data.msg);
    							serverTable.draw(false);
    							serverTable2.draw(false);
    							$("#right").mLoading("hide");
    						}
    					});
    				}
    				$(this).closeDialog(modal);
    			}
    		});
    }
    
    //编辑已绑定部件区域的部件信息
    function editInfo(data){
        if(!data) return;
        jQuery('#partId').val(data.id);
        jQuery('#partName').val(data.partName);
        jQuery('#manufacturer').val(data.manufacturer);
        jQuery('#productionTime').val(moment(data.productionTime).format('YYYY-MM-DD'));
        jQuery('#installationTime').val(moment(data.installationTime).format('YYYY-MM-DD'));
        jQuery('#state').val(data.state.id);
        jQuery('#deviceIdentify').val(data.deviceIdentify);
        
        jQuery('#interfaceAddress1').val(data.interfaceAddress);
        jQuery('#interfacePort1').val(data.interfacePort);
        
        var file = $("#file") 
		file.after(file.clone().val("")); 
		file.remove();
        
		var iconAddress = data.iconAddress;
		if (typeof (iconAddress) != 'undefined' && iconAddress != '') {
			iconAddress = window.rootPath + '/' + iconAddress;
		} else {
			iconAddress = '../img/upload.png';
		}
		$("#avatar").attr('src', iconAddress);
		
        jQuery('.hide-div').hide();
        jQuery('.hide-input').hide();
		if(partType == '0'){
			
		}else if(partType == '1'){
			jQuery('#videoInfoDiv').show();
			jQuery('#videoInfoDiv .hide-input').show();
		}
        jQuery('#editModal').modal('show');
    };
    
    //隐藏datatable列
    function fnShowHide(iCol,bVisible){
    		var oTable = $('#dataTable2').dataTable();
    		oTable.fnSetColumnVis( iCol , bVisible);
    	}
})();